package com.lagou.rpc.provider.schedule;

import org.apache.curator.framework.CuratorFramework;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author liuc
 * @date 2021/6/8
 * @description
 **/
public class TimeRecorder extends Thread{

    private boolean running = true;
    private static BlockingQueue<Long> queue = new ArrayBlockingQueue<>(100);
    private String path;
    private CuratorFramework client;
    private int rpcPort;

    public TimeRecorder(String path, CuratorFramework client, int port){
        this.path = path;
        this.client = client;
        this.rpcPort = port;
    }

    public void add(Long time){
        queue.offer(time);
    }

    @Override
    public void run() {
        while (running){
            try {
                Long time = queue.poll(5, TimeUnit.SECONDS);
                byte[] bytes = client.getData().forPath(path);
                String data = new String(bytes);
                String[] arr = data.split(";");
                if(time != null){
                    System.out.println(rpcPort + " time is " + time);
                    client.setData().forPath(path,(arr[0]+";"+time).getBytes());
                }else{
                    if(arr.length > 1){
                        client.setData().forPath(path,arr[0].getBytes());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void shutDown(){
        this.running = false;
    }
}
